#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>
#include "Log.hpp"
#include"IntAddr.hpp"
using namespace MyLog;

const std::string defaultdir = "./dir.txt";
const std::string sep = ": ";
class dir
{
public:
    dir(const std::string path = defaultdir) : _path(path)
    {
    }
    bool LoadDir()
    {
        std::ifstream in(_path);

        if (!in.is_open())
        {
            LOG(Loglevel::WARN) << "加载字典失败,路径: " << _path;
            return false;
        }
        std::string line;
        while (getline(in, line))
        {
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(Loglevel::DEBUG) << "加载错误";
                continue;
            }
            std::string en = line.substr(0, pos);
            std::string ch = line.substr(pos + sep.size());

            if (en.empty() || ch.empty())
            {
                LOG(Loglevel::DEBUG) << "没有有效内容";
                continue;
            }

            _dir.insert(std::make_pair(en, ch));
            LOG(Loglevel::INFO) << "加载: " << line;
        }
        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dir.find(word);
        if (iter == _dir.end())
        {
            LOG(Loglevel::INFO) << "进入翻译模块 " << "[" << client.Ip() << ":" << client.Port() << "] " << word << "->None";
            return "None";
        }
        LOG(Loglevel::INFO) << "进入翻译模块 " << "[" << client.Ip() << ":" << client.Port() << "] " << word << "->" << iter->second;
        return iter->second;
    }

private:
    std::unordered_map<std::string, std::string> _dir;
    std::string _path;
};